package dynamojunit;

import java.util.*;

import Common.TraceWriter;

import com.amazonaws.services.dynamodb.model.*;

public class UserSessionTable
{
	private static final String TABLE_NAME = "UserSessionTable"; 
	private static final String TABLE_KEY = "sessionId";
	private static final String TABLE_START_TIME_KEY = "startTime";
	private static final String TABLE_WORKFLOW_ID_KEY = "workFlowId";
		
	public UserSessionTable(boolean shouldInitTable)
	{
		if (shouldInitTable)
		{
			DynamoDbCommon.initTable(TABLE_NAME, TABLE_KEY);
		}
	}
	
	private boolean isSessionIdExist(String sessionId)
	{
		return DynamoDbCommon.isMatchingEntryExist(TABLE_NAME, TABLE_KEY, sessionId);
	}
	
	public String getSessionCurrentWorkflowId(String sessionId)
	{
		if (!isSessionIdExist(sessionId))
		{
			return "";
		}
		Map<String,AttributeValue> values = DynamoDbCommon.readUniqueEntry(TABLE_NAME, TABLE_KEY, sessionId);
		for (Map.Entry<String, AttributeValue> entry: values.entrySet())
		{
			if (entry.getKey()==TABLE_WORKFLOW_ID_KEY)
			{
				return entry.getValue().getS();
			}
		}
		return "";
	}
	
	public void insertSessionWorkFlow(String sessionID, String workflowId)
	{
		if (!isSessionIdExist(sessionID))
		{
			TraceWriter.trace("insertSessionWorkFlow: creating new session entry");
			
			Date dateNow = new Date();
			Map<String, AttributeValue> item = newSessionItem(sessionID, workflowId, dateNow.getTime());
			DynamoDbCommon.putItemWithConsistency(TABLE_NAME, TABLE_KEY, item);
			return;
		}
		else
		{
			updateSessionWorkFlow(sessionID, workflowId);
		}
	}
	
	public void updateSessionWorkFlow(String sessionID, String workflowId)
	{
		if (isSessionIdExist(sessionID))
		{
			Key key = new Key(new AttributeValue(sessionID));
			Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
			updates.put(TABLE_WORKFLOW_ID_KEY, new AttributeValueUpdate(new AttributeValue().withS(workflowId), "PUT"));
			
			DynamoDbCommon.updateItem(TABLE_NAME, key, updates);
		}
	}
	
    private static Map<String, AttributeValue> newSessionItem(String sessionID, String workflowId, long startTime)
    {
        Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
        
        item.put(TABLE_KEY, new AttributeValue(sessionID));
        item.put(TABLE_WORKFLOW_ID_KEY, new AttributeValue(workflowId));
        item.put(TABLE_START_TIME_KEY, new AttributeValue().withN(Long.toString(startTime)));

        return item;
    }

}
